package com.fau.mm.security;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.SecurityMetadataSource;
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
import org.springframework.security.access.intercept.InterceptorStatusToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

@Service
public class MySecurityFilter extends AbstractSecurityInterceptor implements
		Filter {
	
	private AccessDecisionManager myAccessDecisionManager;
	private FilterInvocationSecurityMetadataSource  mySecurityMetadataSource;
	private AuthenticationManager authenticationManager;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		FilterInvocation fi = new FilterInvocation(arg0, arg1, arg2);
		invoke(fi);
	}
	
	private void invoke(FilterInvocation fi) throws IOException, ServletException{
		InterceptorStatusToken token = super.beforeInvocation(fi);
		try {
			fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
		}finally {
			super.afterInvocation(token, null);
		}
	}
	
	@PostConstruct
	public void init(){
		super.setAccessDecisionManager(myAccessDecisionManager);
		super.setAuthenticationManager(authenticationManager);
	}
	
	@Override
	public void init(FilterConfig arg0) throws ServletException {}

	@Override
	public Class<?> getSecureObjectClass() {
		return FilterInvocation.class;
	}

	@Override
	public SecurityMetadataSource obtainSecurityMetadataSource() {
		return this.mySecurityMetadataSource;
	}

	public AccessDecisionManager getMyAccessDecisionManager() {
		return myAccessDecisionManager;
	}

	@Resource
	public void setMyAccessDecisionManager(
			AccessDecisionManager myAccessDecisionManager) {
		this.myAccessDecisionManager = myAccessDecisionManager;
	}

	public FilterInvocationSecurityMetadataSource getMySecurityMetadataSource() {
		return mySecurityMetadataSource;
	}

	@Resource
	public void setMySecurityMetadataSource(
			FilterInvocationSecurityMetadataSource mySecurityMetadataSource) {
		this.mySecurityMetadataSource = mySecurityMetadataSource;
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	@Resource
	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

}
